package com.exchange.service.mybatis;

import com.exchange.dto.ProductDto;
import com.exchange.entity.Product;
import com.exchange.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class MyBatisProductService {
    
    @Autowired
    private ProductMapper productMapper;
    
    public Optional<Product> findById(Long id) {
        Product product = productMapper.selectById(id);
        return Optional.ofNullable(product);
    }
    
    public List<ProductDto> findByMerchantId(Long merchantId) {
        return productMapper.selectByMerchantId(merchantId);
    }
    
    public ProductDto createProduct(Product product) {
        // Set creation timestamps
        product.setCreatedAt(java.time.LocalDateTime.now());
        product.setUpdatedAt(java.time.LocalDateTime.now());
        
        // Insert the product
        productMapper.insert(product);
        
        // Return DTO representation
        return ProductDto.fromEntity(product);
    }
    
    public ProductDto updateProduct(Long id, Product product) {
        // Find the existing product
        Product existingProduct = productMapper.selectById(id);
        if (existingProduct != null) {
            // Update properties
            existingProduct.setName(product.getName());
            existingProduct.setDescription(product.getDescription());
            existingProduct.setImageUrl(product.getImageUrl());
            existingProduct.setPrice(product.getPrice());
            existingProduct.setStockQuantity(product.getStockQuantity());
            existingProduct.setCategory(product.getCategory());
            existingProduct.setStatus(product.getStatus());
            existingProduct.setUpdatedAt(java.time.LocalDateTime.now());
            
            // Perform update in database
            productMapper.update(existingProduct);
            
            // Return DTO representation
            return ProductDto.fromEntity(existingProduct);
        }
        return null;
    }
    
    public boolean deleteProduct(Long id) {
        int result = productMapper.deleteById(id);
        return result > 0;
    }
}